package com.yiyi.credit.manage.abutment.common.utils;

import org.apache.commons.lang.CharRange;
import org.apache.commons.lang.CharSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringUtil {
    private static final Logger logger = LoggerFactory.getLogger(StringUtil.class);
    private final static CharRange digit = new CharRange('\u0030', '\u0039');
    private static CharSet alphaNumChar = CharSet.getInstance("0-9A-Za-z");

    public static String createRandomString(int length, boolean isNumber) {
        int NUM_CHAR = 59;
        if (isNumber)
            NUM_CHAR = 10;

        String t = "";
        int j = 0;
        String[] v = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a",
                "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "m", "n",
                "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
                "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M",
                "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

        for (int i = 0; i < length; i++) {
            j = (int) (NUM_CHAR * Math.random());
            t = t + v[j];
        }

        return t;
    }


    public static int stringToInt(String pInt) {
        return pInt == null || "".equals(pInt) ? 0 : new BigDecimal(pInt)
                .intValue();
    }


    public static String objToStr(Object obj) {
        if (obj == null) {
            return "";
        } else {
            return String.valueOf(obj);
        }
    }


    public static String trim(Object obj) {
        if (obj == null) {
            return "";
        } else {
            return String.valueOf(obj).trim();
        }
    }


    public static String StrTrim(Object obj) {
        if (obj == null) {
            return "";
        } else {
            return String.valueOf(obj).trim();
        }
    }


    public static boolean isEmpty(String str) {
        if (str == null || str.length() == 0) {
            return true;
        } else {
            return false;
        }
    }


    public static boolean strEquals(String pStr1, String pStr2) {
        return pStr1 == null ? pStr2 == null : pStr1.equals(pStr2);
    }


    public static String urlEncode(String str, String code) {
        String result = "";
        try {
            result = URLEncoder.encode(str, code);
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }

        return result;
    }


    public static String urlDecode(String str, String code) {
        String result = "";
        try {
            result = new String(str.getBytes("ISO-8859-1"), code);
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }

        return result;
    }


    public static boolean isDouble(String pInt) {
        try {
            Double.parseDouble(pInt);
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    public static double strToDouble(String doubleStr) {
        if (isEmpty(doubleStr)) {
            return Double.parseDouble("0.0");
        }
        try {
            return new BigDecimal(doubleStr).doubleValue();
        } catch (Exception e) {
            return Double.parseDouble("0.0");
        }
    }


    public static float strToFloat(String str) {
        if (isEmpty(str)) {
            return Float.parseFloat("0.0");
        }
        try {
            return new BigDecimal(str).floatValue();
        } catch (Exception e) {
            return Float.parseFloat("0.0");
        }
    }


    public static int getUtf8Bytes(String src) {
        if (isEmpty(src)) {
            return 0;
        } else {
            try {
                return src.getBytes("UTF-8").length;
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return 0;
    }


    public static String[] split(String pInt, String dot) {
        return pInt.split(dot, -1);
    }


    public static int length(String str) {
        if (str == null) {
            return 0;
        } else {
            return str.length();
        }
    }


    public static boolean isAsciiAlphaNumCharOnly(String str) {
        boolean asciiOnly = true;
        if (StringUtil.isEmpty(str)) {
            return asciiOnly;
        }
        char[] cs = str.toCharArray();
        for (int i = 0; i < cs.length; i++) {
            if (!alphaNumChar.contains(cs[i])) {
                asciiOnly = false;
            }
        }
        return asciiOnly;
    }


    public static boolean isDigit(String str) {
        boolean isdigit = false;
        if (isEmpty(str)) {
            return isdigit;
        }
        isdigit = true;
        char[] cs = str.toCharArray();
        for (int i = 0; i < cs.length; i++) {
            if (!digit.contains(cs[i])) {
                isdigit = false;
            }
        }
        return isdigit;
    }


    public static boolean isCountNum(String str, int count) {
        if (StringUtil.isEmpty(str)) {
            return false;
        }
        if (str.length() > count) {
            return false;
        }
        return isDigit(str);
    }


    public static boolean is6Num(String str) {
        if (StringUtil.isEmpty(str)) {
            return true;
        }
        String reg = "^([1-9][0-9]{5})$";
        Pattern pat = Pattern.compile(reg);
        Matcher mat = pat.matcher(str);
        boolean rs = mat.find();
        return rs;
    }


    public static boolean is2numeric(String str) {
        if (StringUtil.isEmpty(str)) {
            return true;
        }
        String reg = "^([0-9]{2})$";
        Pattern pat = Pattern.compile(reg);
        Matcher mat = pat.matcher(str);
        boolean rs = mat.find();
        return rs;
    }


    public static boolean is01num(String str) {
        if (StringUtil.isEmpty(str)) {
            return true;
        }
        String reg = "^(0([\\.]\\d*[0-9]+)|0|1)$";
        Pattern pat = Pattern.compile(reg);
        Matcher mat = pat.matcher(str);
        boolean rs = mat.find();
        return rs;
    }


    public static long strToLong(String str) {
        if (isEmpty(str)) {
            return 0;
        }
        try {
            return Long.parseLong(str);
        } catch (Exception e) {
            return 0;
        }
    }


    public static boolean isLong(String str) {
        if (isEmpty(str)) {
            return false;
        }
        try {
            Long.parseLong(str);
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    public static boolean isInteger(String str) {
        if (isEmpty(str)) {
            return false;
        }
        try {
            Integer.parseInt(str);
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    public static boolean isBlank(String str) {
        int length;

        if ((str == null) || ((length = str.length()) == 0)) {
            return true;
        }

        for (int i = 0; i < length; i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return false;
            }
        }

        return true;
    }


    public static boolean isMobile(String mobile) {

        String regex = "(\\+\\d+)?1[34578]\\d{9}$";
        return Pattern.matches(regex, mobile);

    }


    public static boolean isSpechars(String str) {
        if (StringUtil.isEmpty(str)) {
            return false;
        }
        String reg = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern pat = Pattern.compile(reg);
        Matcher mat = pat.matcher(str);
        boolean rs = mat.find();
        return rs;
    }


    public static String IgnoreStrPlus(String str) {
        if (!isEmpty(str)) {
            str = str.replace("[", "［");
            str = str.replace("\t", "");
            str = str.replace("%", "％");
            str = str.replace("^", "＾");
            str = str.replace("*", "＊");
            str = str.replace("(", "（");
            str = str.replace(")", "）");
            str = str.replace("'", "’");
            str = str.replace("[", "［");
            str = str.replace("]", "］");
            str = str.replace("<", "＜");
            str = str.replace(">", "＞");
            str = str.replace("\"", "”");
            return str;
        } else {
            return "";
        }
    }


    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }


    public static boolean isPs(String str) {
        if (StringUtil.isEmpty(str)) {
            return true;
        }
        String reg = "^.{6,32}$";
        Pattern pat = Pattern.compile(reg);
        Matcher mat = pat.matcher(str);
        boolean rs = mat.find();
        return rs;
    }


    public static boolean isPhoneNumberValid(String phoneNumber) {
        if (isMobile(phoneNumber))
            return true;
        boolean isValid = false;
        String expression = "[0]{1}[0-9]{2,3}-[0-9]{7,8}";
        CharSequence inputStr = phoneNumber;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }

    public static String getRandomUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }


    public static String humpToUnderScore(String str) {
        if (StringUtils.isEmpty(str))
            return str;

        char[] chars = str.toCharArray();
        StringBuilder stringBuilder = new StringBuilder();
        int lastLowercaseIdx = -1;
        for (int i = 0; i < chars.length; i++) {
            char ch = chars[i];
            if (Character.isLowerCase(ch)) {
                lastLowercaseIdx = i;
                stringBuilder.append(ch);
            } else if (lastLowercaseIdx > 0 && lastLowercaseIdx + 1 == i) {
                stringBuilder.append("_").append(Character.toLowerCase(ch));
            } else {
                stringBuilder.append(ch);
            }
        }

        return stringBuilder.toString();
    }

    public static String encodePhoneNum(String phoneNum) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(phoneNum))
            return phoneNum;

        if (phoneNum.length() < 3) {
            return phoneNum;
        }

        return phoneNum.substring(0, 3) + "****" + phoneNum.substring(phoneNum.length() - 3, phoneNum.length());
    }

    public static String nullToEmptyString(Object obj) {
        return obj == null ? "" : obj + "";
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }
}
